package graph.poj2421;
 
import java.util.Scanner;
 
public class POJ2421 {
    static final int maxn = 105;
    static final int inf = 0x3f3f3f3f;
    static int m[][] = new int[maxn][maxn];
    static int low[] = new int[maxn];
    static boolean vis[] = new boolean[maxn];
    static int n;
 
    static int prim(int s) {
        for (int i = 0; i < vis.length; i++) {
            vis[i] = false;
        }
        for (int i = 1; i <= n; i++)
            low[i] = m[s][i];
        vis[s] = true;
        int sum = 0;
        int t = 1;
        for (int i = 1; i < n; i++) { // 执行 n-1 次
            int min = inf;
            for (int j = 1; j <= n; j++) { // 找最小
                if (!vis[j] && low[j] < min) {
                    min = low[j];
                    t = j;
                }
            }
            sum += min;
            vis[t] = true;
            for (int j = 1; j <= n; j++) {//更新
                if (!vis[j] && low[j] > m[t][j])
                    low[j] = m[t][j];
            }
        }
        return sum;
    }
 
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int q, a, b;
        while (true) {
            n = scanner.nextInt();
            if (n == 0) {
                return;
            }
            for (int i = 1; i <= n; i++)
                for (int j = 1; j <= n; j++)
                    m[i][j] = scanner.nextInt();
            q = scanner.nextInt();
            while (q-- > 0) {
                a = scanner.nextInt();
                b = scanner.nextInt();
                m[a][b] = m[b][a] = 0;
            }
            System.out.println(prim(1));
        }
    }
}